const bcrypt =  require('bcryptjs')
const { sequelize } = require("../../core/db");
const { Sequelize : db, Model } = require('sequelize');
const { notFound } = require('../../core/http-exception');
class User extends Model {
    static async verifyAccount(account,secret){
       const user = await User.findOne({
            where:{
                email:account,
            }
        })
        if(!user){
        throw new notFound('邮箱不存在！')
        }
        const pwd = bcrypt.compareSync(secret,user.password)
        if(!pwd){
            throw new notFound('密码不正确！')
        }
        return user
    }
}

User.init({
    nickName: {
        type: db.STRING,
        //unique:true,//是否是唯一的
    },
    email:{
        type: db.STRING,
    },
    password:{
        type: db.STRING,
        set(val){
            const salt = bcrypt.genSaltSync(10)
            const pwd = bcrypt.hashSync(val,salt)
            this.setDataValue('password',pwd)
        }
    },
    openId:{
        type: db.STRING(64),
    }
}, {
    sequelize,
    tableName:'user',//指定数据库表名
})

module.exports = {
    User
}